﻿function showMessage(request, msg) {
    var temp = eval("(" + request.responseText + ")");
    alert(msg + "\nDetail: " + temp.Message);
}

(function ($) {
    $.fn.upload = function (vm) {
        return this.each(function () {
            $(this).fileupload({
                url: '/handler.ashx',
                dataType: 'json',
                // autoUpload: true,
                acceptFileTypes: /(\.|\/)(doc|doc?x|xls|xls?x|pdf)$/i,
                maxFileSize: 10000000, // 10 MB
                // Enable image resizing, except for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
                previewMaxWidth: 100,
                previewMaxHeight: 100,
                previewCrop: true
            }).on('fileuploadprogressall', function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css('width', progress + '%');
            }).on('fileuploaddone', function (e, data) {
                $.each(data.result.files, function (index, file) {
                    // append
                    vm.documents.push({ originname: file.OriginName, name: file.Name, pages: file.Pages, copies: 1 });
                });
                var valid = $('#button-upload').parent().find('.validate');
                if (valid.length)
                    valid.remove();
            }).on('fileuploadfail', function () {
                //                $.each(data.result.files, function(index, file) {
                //                    // show error message
                //                    vm.documents.push({ originname: file.OriginName, name: file.Name, pages: file.Pages, copies: 2 });
                //                });
            }).prop('disabled', !$.support.fileInput)
                .parent().addClass($.support.fileInput ? undefined : 'disabled');
        });
    };
})(jQuery);

$.urlParam = function (name, url) {
    if (!url) {
        url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) {
        return 0;
    }
    return results[1] || 0;
};

function DocumentVM() {
    var self = this;
    self.documents = ko.observableArray([]);

    self.submit = function () {
        if ($('form .validate').length) return false;
        if ($('#neededDate').val() == '') {
            //            $('#neededDate').parent().append('<label class="validate" style="color: red" title="Needed date is a required.">*</label>');
            $.prompt("Needed date is a require field.");
            return false;
        }
        var cate = $('.category option:selected').val();
        var signBy = $('input[name=signBy]:checked').val();
        if (cate == '0' && signBy == '2') {
            $.prompt("Category and Sign by field does not match.");
            return false;
        }
        if (cate != '0' && signBy == '1') {
            $.prompt("Category and Sign by field does not match.");
            return false;
        }
        if ($('#purposeOfDoc').val() == '') {
            $.prompt("Purpose of document is a require field.");
            return false;
        }
		
		if(!$('input[name=stampedType]:checked').length) {
			$.prompt("Stamp type is a require field.");
			return false;
		}
		
        $.prompt("Do you want to save this stamp request?", {
            title: "Confirm",
            buttons: { "Yes": true, "Cancel": false },
            submit: function (e, v) {
                if (!v) return;

                var documents = [];
                $.each(self.documents(), function () {
                    documents.push({
                        Link: this.name,
                        OriginName: this.originname
                    });
                });

                var a = [];
                $('input[name=stampedType]:checked').each(function() {
                    a.push(parseInt($(this).val()));
                });

                $.ajax({
                    type: "POST",
                    url: "/Pages/RequestForm.aspx/SaveRequest",
                    data: JSON.stringify({
                        request: {
                            RequestID: $('#hidRequestId').val(),
                            AssignedTo: $('#hidAssignedTo').val(),
                            Purpose: $('#purposeOfDoc').val(),
                            Remark: $('#remark').val(),
                            RequestFor: $('.requestFor option:selected').val(),
                            CategoryId: $('.category option:selected').val(),
                            SignByID: $('input[name=signBy]:checked').val(),
                            RequestType: parseInt($('.requestType option:selected').val()),
                            RequiredBy: $('input[name=requiredBy]:checked').val(),
                            STList: a,
                            StampID: $('input[name=stamped]:checked').val(),
                            DefineName: $('#defineName').val(),
                            DateNeeded: $('#neededDate').val(),
                            PagesNo: $("#numPages").spinner("value"),
                            CopiesNo: $('#numCopies').spinner("value"),
                            DocumentList: documents
                        }
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        if (data.d) {
                            $.prompt('You have registered successfully.');
                            window.location.href = '/';
                        }
                    },
                    error: function (xmlHttpRequest) {
                        showMessage(xmlHttpRequest, 'Failed');
                        return false;
                    }
                });
            }
        });

        return false;
    };

    self.getItem = function (requestId) {

        $.ajax({
            type: "POST",
            url: "/Pages/RequestForm.aspx/GetItem",
            data: JSON.stringify({ requestId: requestId }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                var request = data.d;
                $('#hidRequestId').val(request.RequestID);
                $('#hidAssignedTo').val(request.AssignedTo);
                $('.deptName').val(request.DeptName);
                $('.requestFor').val(request.RequestFor);
                $('.category').val(request.CategoryId);
                $('.requestType').val(request.RequestType);
                $('.dateOfApp').val(request.DateRequestText);
                $('#neededDate').val(request.DateNeededText);
                $('#purposeOfDoc').val(request.Purpose);
                $('#defineName').val(request.DefineName);
                $('#remark').val(request.Remark);
                $("#numPages").spinner("value", request.PagesNo);
                $('#numCopies').spinner("value", request.CopiesNo);
                $('input[name=signBy][value=' + request.SignByID + ']').prop('checked', true);
                $('input[name=requiredBy][value=' + request.RequiredBy + ']').prop('checked', true);
                $.each(request.STList, function() {
                    $('input[name=stampedType][value=' + this + ']').prop('checked', true);
                });
                $('input[name=stamped][value=' + request.StampID + ']').prop('checked', true);
                if (request.DocumentList != null) {
                    $.each(request.DocumentList, function() {
                        self.documents.push({
                            originname: this.OriginName,
                            name: this.Link
                        });
                    });
                }
            },
            error: function () {
            }
        });

        return false;
    };

    self.reset = function () {

        $('#neededDate').val('');
        $('#purposeOfDoc').val('');
        $('#defineName').val('');
        $('#remark').val('');
        $('.requestFor').val(null);
        $('.requestType').val('1');
        $('.category').val(null);
        $("#numPages").spinner("value", 1);
        $('#numCopies').spinner("value", 1);
        $('input[name=signBy][value=1]').prop('checked', true);
        $('input[name=requestType][value=1]').prop('checked', true);
        $('input[name=requiredBy][value=1]').prop('checked', true);
        $('input[name=stamped][value=1]').prop('checked', true);

        $('input[name=stampedType]').each(function () {
            $(this).prop('checked', false);
        });

        var filepaths = [];
        $.each(self.documents(), function () {
            filepaths.push(this.name);
        });
        $.ajax({
            type: "POST",
            url: "/Pages/RequestForm.aspx/DeleteFiles",
            data: JSON.stringify({ filepaths: filepaths }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function () {
                self.documents.removeAll();
            },
            error: function () {
            }
        });

        return false;
    };

    self.removeItem = function (item) {

        if ($('#hidRequestId').val() != '') {
            $.prompt("Do you want to remove this file?", {
                title: "Confirm",
                buttons: { "Yes": true, "Cancel": false },
                submit: function (e, v) {
                    if (!v) return;
                    $.ajax({
                        type: "POST",
                        url: "/Pages/RequestForm.aspx/DeleteDocument",
                        data: JSON.stringify({ requestId: $('#hidRequestId').val(), filepath: item.name }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: false,
                        success: function() {
                            self.documents.remove(item);
                        },
                        error: function() {
                        }
                    });
                }
            });
        } else {
            $.ajax({
                type: "POST",
                url: "/Pages/RequestForm.aspx/DeleteFile",
                data: JSON.stringify({ filepath: item.name }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function() {
                    self.documents.remove(item);
                },
                error: function() {
                }
            });
        }
    };
}

$(document).ready(function () {
    var today = new Date();

    $("#numPages").spinner({
        spin: function (event, ui) {
            if (ui.value > 500 || ui.value < 1) {
                return false;
            }
            return true;
        }
    });

    $("#numCopies").spinner({
        spin: function (event, ui) {
            if (ui.value > 2000 || ui.value < 1) {
                return false;
            }
            return true;
        }
    });

    $(".needed-date.datepicker").datepicker({
        changeMonth: true,
        numberOfMonths: 1,
        showOn: "button",
        minDate: today,
        onSelect: function () {
            var valid = $('.needed-date.datepicker').parent().find('.validate');
            if (valid.length)
                valid.remove();
        }
    });

    var vm = new DocumentVM();
    $('#button-upload').upload(vm);
    $(":file").jfilestyle({ input: false, buttonText: "Upload", theme: "blue" });
    ko.applyBindings(vm);

    var requestId = $.urlParam('q');
    if (requestId.length) {
        vm.getItem(requestId);
    }
    $("input[type='number']").stepper();

    // Check only 1 in 2 or none check
    $('input[name=signBy]').on('change', function () {
        $('input[name=signBy]').not(this).prop('checked', false);
    });

    // Check only 2 in 3 or none check
    $('input.only-one[name=stampedType]').on('change', function () {
        $('input.only-one[name=stampedType]').not(this).prop('checked', false);
    });

    $('#submit').click(vm.submit);
    $('#reset').click(vm.reset);
});